import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
} from 'react'
import * as echarts from 'echarts'
import { useTheme } from '@/contexts/ThemeContext'
import dayjs from 'dayjs'
import { LOOP_TIME_MIL } from '@/config/env'
import { useGlobalContext } from '@/contexts/GlobalContext'

// 定义组件接收的 ref 类型
interface TotalOverviewRef {
  handleResize: () => void
}

// 定义组件接收的 props 类型
interface TotalOverviewProps {
  title: string
  total: number
  disposedSum: number
}

// 正确使用 forwardRef 的 TypeScript 定义
const TotalOverview = forwardRef<TotalOverviewRef, TotalOverviewProps>(
  (props, ref) => {
    const { title, total, disposedSum } = props
    const { isLoop } = useGlobalContext()
    const chartRef = useRef<HTMLDivElement>(null)
    const chartInstance = useRef<echarts.ECharts | null>(null)
    const { isDark, currentTheme } = useTheme()
    const overviewTimer = useRef<NodeJS.Timeout | null>(null)
    useEffect(() => {
      if (chartRef.current) {
        chartInstance.current = echarts.init(chartRef.current)

        const option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
            },
          },
          legend: {
            data: ['告警数量', '处理数量'],
            textStyle: {
              color: currentTheme.token?.colorText,
            },
            right: 10,
            top: 0,
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            data: [],
            axisLine: {
              lineStyle: {
                color: 'rgba(0, 149, 255, 0.5)',
              },
            },
            axisLabel: {
              color: 'rgba(255, 255, 255, 0.7)',
            },
          },
          yAxis: {
            type: 'value',
            axisLine: {
              show: false,
            },
            axisLabel: {
              color: 'rgba(255, 255, 255, 0.7)',
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(0, 149, 255, 0.1)',
              },
            },
          },
          series: [
            {
              name: '告警数量',
              type: 'line',
              smooth: true,
              data: [total],
              lineStyle: {
                width: 3,
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: '#00d4ff' },
                  { offset: 1, color: '#0066ff' },
                ]),
              },
              symbol: 'circle',
              symbolSize: 8,
              itemStyle: {
                color: '#00d4ff',
                borderColor: '#fff',
                borderWidth: 2,
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(0, 212, 255, 0.3)' },
                  { offset: 1, color: 'rgba(0, 212, 255, 0.1)' },
                ]),
              },
            },
            {
              name: '处理数量',
              type: 'line',
              smooth: true,
              data: [disposedSum],
              lineStyle: {
                width: 3,
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: '#00ffaa' },
                  { offset: 1, color: '#0099ff' },
                ]),
              },
              symbol: 'circle',
              symbolSize: 8,
              itemStyle: {
                color: '#00ffaa',
                borderColor: '#fff',
                borderWidth: 2,
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(0, 255, 170, 0.3)' },
                  { offset: 1, color: 'rgba(0, 255, 170, 0.1)' },
                ]),
              },
            },
          ],
        }

        chartInstance.current.setOption(option)
        updateLineAxis()
        window.addEventListener('resize', handleResize)

        return () => {
          window.removeEventListener('resize', handleResize)
          chartInstance.current?.dispose()
          overviewTimer.current && clearInterval(overviewTimer.current)
        }
      }
    }, [])
    useEffect(() => {
      if (isLoop) {
        updateLineAxis()
      } else {
        overviewTimer.current && clearInterval(overviewTimer.current)
      }
    }, [isLoop])
    // 切换主题，样式调整
    useEffect(() => {
      chartInstance.current?.setOption({
        legend: {
          textStyle: {
            color: currentTheme.token?.colorText,
          },
        },
        xAxis: {
          axisLabel: {
            color: currentTheme.token?.colorText,
          },
        },
        yAxis: {
          axisLabel: {
            color: currentTheme.token?.colorText,
          },
        },
      })
    }, [isDark])
    function updateLineAxis() {
      if (overviewTimer.current) {
        clearInterval(overviewTimer.current)
      }
      overviewTimer.current = setInterval(() => {
        const currentTime = dayjs().format('HH:mm:ss')
        const currentOption = chartInstance.current?.getOption() as any
        if (currentOption?.xAxis?.[0]?.data?.length >= 10) {
          currentOption.xAxis[0].data.shift()
          currentOption.series[0].data.shift()
          currentOption.series[1].data.shift()
        }
        currentOption.xAxis[0].data.push(currentTime)
        currentOption.series[0].data.push(total)
        currentOption.series[1].data.push(disposedSum)
        chartInstance.current?.setOption(currentOption)
      }, LOOP_TIME_MIL)
    }
    const handleResize = () => {
      chartInstance.current?.resize()
    }

    // 使用 useImperativeHandle 暴露方法给父组件
    useImperativeHandle(ref, () => ({
      handleResize,
    }))

    return (
      <div className="panel flex-1 scroll-container">
        <div className="panel-title">{title}</div>
        <div style={{ display: 'flex', gap: '15px', marginBottom: '15px' }}>
          <div className="stats-card">
            <div className="stats-label">今日告警总数</div>
            <div className="stats-value">{total}</div>
          </div>
          <div className="stats-card">
            <div className="stats-label">已处理告警</div>
            <div className="stats-value blink">{disposedSum}</div>
          </div>
        </div>
        <div ref={chartRef} className="chart-container"></div>
      </div>
    )
  }
)

export default TotalOverview
